package info.vanbeem.WikiMindDesktop;

import java.io.IOException;
import java.util.regex.Pattern;

import org.apache.commons.lang.SystemUtils;

import com.admc.jcreole.JCreole;

class WikiParser extends JCreole {

	public WikiParser() {
	}

	public WikiParser(String template) {
		super(template);
	}

	public String parse(final String text) throws IOException {
		//return preparseWikiMindStyle(text).toString();
		///*
		String htmlfragment = parseCreole(preparseWikiMindStyle(text));
        return postProcess(htmlfragment, SystemUtils.LINE_SEPARATOR);
        //*/
	}
	
	private StringBuilder preparseWikiMindStyle(String text) {
		String lines[] = text.split("[ \\t\\r]*\\n", -1);		// Split in lines and clear trailing white spaces.
		StringBuilder result = new StringBuilder();
		Pattern specialend = Pattern.compile(".*=");
		Pattern specialstart = Pattern.compile("[#=\\*]+.*");
		 
		for (int cnt = 0; cnt < lines.length - 1; cnt++) {
			String thisline = lines[cnt].replace("<<", "~<<");	// Escape extensions (not supported by WikiMind).
			String nextline = lines[cnt + 1];

			if (thisline.length() == 0) {
				result.append("\n\\\\\n");	// Force an empty line.
			}
			else if (specialend.matcher(thisline).matches() || specialstart.matcher(nextline).matches()) {
				result.append(thisline);
				result.append("\n");		// No extra's needed, because of special lines (headings, enums).
			}
			else
			{
				result.append(thisline);
				result.append("\n\n");		// Force a paragraph end.
			}
		}
		if (lines.length > 0) result.append(lines[lines.length - 1]);
		
		return result;
	}
}
